package com.cuanbobox.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;

import androidx.annotation.NonNull;

import com.cuanbobox.activity.MainActivity;
import com.cuanbobox.base.App;
import com.cuanbobox.bean.EventBusBean;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Camera2Helper {
    private ImageReader mImageReader;
    private Activity aty;
    public CameraDevice mCameraDevice;
    private CaptureRequest.Builder mCaptureRequest;
    private int width;
    private int height;
    private TextureView textureView;
    private CameraCaptureSession session;

    public Camera2Helper(Activity aty, TextureView textureView, int width, int height) {
        this.aty = aty;
        this.width=width;
        this.height=height;
        this.textureView=textureView;
    }

    @SuppressLint("MissingPermission")
    public void start() {
        try {
            CameraManager cameraManager = (CameraManager) aty.getSystemService(Context.CAMERA_SERVICE);
            String[] cameraIds = cameraManager.getCameraIdList();
            for(int i=0;i<cameraIds.length;i++){
                Log.i("摄像头"+i,cameraIds[i]);
            }
            //CameraCharacteristics characteristics =cameraManager.getCameraCharacteristics("0");
            cameraManager.openCamera("0", new CameraDevice.StateCallback() {
                @Override
                public void onOpened(CameraDevice camera) {
                    mCameraDevice = camera;
                    startPreview(camera);
                }

                @Override
                public void onDisconnected(CameraDevice camera) {
                    camera.close();
                    mCameraDevice = null;
                }

                @Override
                public void onError(CameraDevice camera, int error) {
                    camera.close();
                    mCameraDevice = null;
                }
            }, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        try{
            if (mCameraDevice != null) {
                mCameraDevice.close();
                mCameraDevice = null;

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void startPreview(CameraDevice camera) {
        try {
            SurfaceTexture mSurfaceTexture=textureView.getSurfaceTexture();
            mSurfaceTexture.setDefaultBufferSize(width,height);
/*            mSurfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {
                @Override
                public void onFrameAvailable(SurfaceTexture surfaceTexture) {
                    surfaceTexture.
                }
            });*/
            Surface surface=new Surface(mSurfaceTexture);
            mCaptureRequest = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mCaptureRequest.addTarget(surface);
            mImageReader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 1);
            mImageReader .setOnImageAvailableListener(mImageReaderListener,null);
            Surface imageSurface = mImageReader.getSurface();
            List<Surface> outputs = new ArrayList<>();
            outputs.add(surface);
            outputs.add(imageSurface);
            mCameraDevice.createCaptureSession(outputs, new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(CameraCaptureSession session) {
                    try {
                        Camera2Helper.this.session=session;
                        CaptureRequest request=mCaptureRequest.build();
                        session.setRepeatingRequest(request, null, null);
                        session.capture(request,new CameraCaptureSession.CaptureCallback(){},new Handler());
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(CameraCaptureSession session) {

                }
            }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }


    }

    public void takePicture() {
        if(mImageReader==null)return;
        try {
            // 创建拍照请求
            CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(mImageReader.getSurface());

            // 设置自动对焦
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_AUTO);

            // 设置闪光灯
            captureBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                    CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);

            // 获取设备方向
            int rotation = aty.getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, rotation);

            session.capture(captureBuilder.build(), new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
                    super.onCaptureFailed(session, request, failure);
                    Log.i("luohao","截图失败");
                }
            }, null);

            // 播放拍照音效或显示闪光灯动画等

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private ImageReader.OnImageAvailableListener mImageReaderListener = new ImageReader.OnImageAvailableListener(){

        @Override
        public void onImageAvailable(ImageReader reader) {
            // 获取到拍照的图像数据
            Image image = reader.acquireLatestImage();

            // 获取图片的字节数组
            ByteBuffer buffer = image.getPlanes()[0].getBuffer();
            byte[] data = new byte[buffer.remaining()];
            buffer.get(data);

            // 保存图片到相册
            saveImageToGallery(data);

            // 释放图像资源
            image.close();
        }

    };

    private void saveImageToGallery(byte[] data) {
        // 创建文件输出流
        try {
            App.capturePath=aty.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/capture/"+ DateUtil.fmtYMD()+"/";
            new File(App.capturePath).mkdirs();
            App.captureFileName=new Date().getTime()+".jpg";
            String path=App.capturePath + App.captureFileName;
            if(MainActivity.comment){
                path=App.commentPath;
            }
            FileOutputStream fos = new FileOutputStream(path);
            fos.write(data);
            fos.close();
            if(MainActivity.comment){
                EventBus.getDefault().post(new EventBusBean(EventBusBean.MODE_COMMENT));
            }
            LogUtil.add("图片保存","成功","拍照");
        } catch (IOException e) {
            e.printStackTrace();
            // 显示保存失败的提示
            LogUtil.add("图片保存","失败","拍照");
        }
    }

}
